/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.feihong.newzxclient.tcp;

import com.google.protobuf.InvalidProtocolBufferException;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import zaoxun.Msg;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * ReceiveHandler implementation for the echo client.  It initiates the ping-pong
 * traffic between the echo client and server by sending the first message to
 * the server.
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = Logger.getLogger(
            NettyClientHandler.class.getName());

    private ChannelHandlerContext mContext;

    private OnReadListener mListener;

    public interface OnReadListener {
        public void read(Object msg) throws InvalidProtocolBufferException;
    }

    public void setOnReadListener(OnReadListener listener) {
        mListener = listener;
    }

    protected void sendMsg(Msg.CommonMessage msg) {
        if (mContext != null) {
            byte[] result = msg.toByteArray();

            ByteBuf buf = Unpooled.buffer(4 + result.length);
            buf.writeInt(result.length);
            buf.writeBytes(result);

            System.out.println("send Msg success!");
            mContext.writeAndFlush(buf);
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        mContext = ctx;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (mListener != null) {
            mListener.read(msg);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.log(Level.WARNING, "Unexpected exception from downstream.", cause);
        ctx.close();
    }
}
